package longshu.srpc;

import lombok.extern.slf4j.Slf4j;
import longshu.srpc.api.RpcProtocol;

import java.io.*;

/**
 * SimpleRpcProtocol
 *
 * @author LongShu 2017/12/03
 */
@Slf4j
public class SimpleRpcProtocol implements RpcProtocol {
    public static final String PROTOCOL = "srpc://";

    public static void register() {
        SimpleRpcProtocol simpleRpcProtocol = new SimpleRpcProtocol();
        ProtocolRegistry.register(simpleRpcProtocol.getProtocol(), simpleRpcProtocol);
        ProtocolRegistry.register(null, simpleRpcProtocol);
        ProtocolRegistry.register("", simpleRpcProtocol);
    }

    @Override
    public byte[] encode(Object object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        try {
            oos.writeObject(object);
            oos.flush();
        } finally {
            IOUtils.close(bos);
            IOUtils.close(oos);
        }
        return bos.toByteArray();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T decode(byte[] bytes, Class<T> genericClass) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        try {
            T object = (T) ois.readObject();
            return object;
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.close(bis);
            IOUtils.close(ois);
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T decode(InputStream in, Class<T> genericClass) throws IOException {
        ObjectInputStream ois = new ObjectInputStream(in);
        try {
            T object = (T) ois.readObject();
            return object;
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public String getProtocol() {
        return PROTOCOL;
    }

}
